package com.zoe.vhr.controller.system.basic;

import cn.hutool.core.convert.Convert;
import com.zoe.vhr.model.Menu;
import com.zoe.vhr.model.Role;
import com.zoe.vhr.service.MenuService;
import com.zoe.vhr.service.RoleService;
import com.zoe.vhr.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/08/05
 * @Description 角色接口
 */
@RestController
@RequestMapping("/system/basic/role")
@Validated
public class RoleController {
    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    @GetMapping("/listAllRoles")
    public R listAllRoles() {
        List<Role> roles = roleService.listAllRoles();
        return R.success(roles);
    }

    @GetMapping("/listAllMenus")
    public R listAllMenus() {
        List<Menu> menus = menuService.listAllMenus();
        return R.success(menus);
    }

    @GetMapping("/listCheckedMenus/{roleId}")
    public R listCheckedMenus(@PathVariable("roleId") Integer roleId) {
        List<Integer> checkedMenus = menuService.listCheckedMenus(roleId);
        return R.success(checkedMenus);
    }

    @PostMapping("/saveRole")
    public R saveRole(@Valid @RequestBody Role role) {
        int count = roleService.saveRole(role);
        if (count > 0) {
            return R.success(role);
        }
        return R.failed("添加失败");
    }

    @PutMapping("/updateMenuWithRole")
    public R updateMenuWithRole(@RequestBody Map<String, Object> map) {
        Integer roleId = Convert.toInt(map.get("roleId"));
        Integer[] menuIds = Convert.toIntArray(map.get("menuIds"));
        int count = menuService.updateMenuWithRole(roleId, menuIds);
        return R.success(count);
    }

    @DeleteMapping("/deleteRole/{roleId}")
    public R deleteRole(@NotNull @PathVariable("roleId") Integer roleId) {
        int count = roleService.deleteRole(roleId);
        if (count > 0) {
            return R.success(count);
        }
        return R.failed("删除失败");
    }
}
